package com.webtest.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import netscape.javascript.JSObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Controller
public class GeoController {
    @Autowired
    private RestTemplate restTemplate;


    @GetMapping("/geo/search")
    public void searchGeo(HttpServletResponse response) throws IOException {
        //处理 some.do请求，相当于service调用处理完成
        Map resultMap = new HashMap<>();
        Map forObject = restTemplate.getForObject("http://ip-api.com/json/", Map.class);
        String lat = forObject.get("lat").toString();
        String lng = forObject.get("lon").toString();
        resultMap.put("lng", lng);
        resultMap.put("lat", lat);
        /*String geo = lat + "," + lng;
        String s = "http://api.map.baidu.com/geocoder?location=" + geo + "&output=json";
        // String geoMap = restTemplate.getForEntity("http://api.map.baidu.com/geocoder?location=" + geo + "&output=json", String.class);
        String geoMap = restTemplate.getForObject("http://api.map.baidu.com/geocoder?location=" + geo + "&output=json", String.class);
        Object parse = JSON.parse(geoMap);
        if (parse instanceof JSONObject) {
            JSONObject JsonResult = (JSONObject) parse;
            Object resultObj = JsonResult.get("result");
            if (resultObj instanceof JSONObject) {
                JSONObject result = (JSONObject) resultObj;
                String string = result.get("formatted_address").toString();
                resultMap.put("address", string);
            }

        }*/

        //将结果对象转为json格式数据
        if (resultMap != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(resultMap);
            System.out.println("student转换的json====" + json);

            //输出数据，响应Ajax请求
            response.setContentType("application/json;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.println(json);
            pw.flush();
            pw.close();
        }
    }
}
